package com.anti_poverty_detection_system.springboot.controller;

import com.anti_poverty_detection_system.springboot.model.*;
import com.anti_poverty_detection_system.springboot.service.*;
import com.anti_poverty_detection_system.springboot.service.dto.UserRequest;
import com.anti_poverty_detection_system.springboot.service.impl.UsersServiceImpl;
import com.anti_poverty_detection_system.springboot.util.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZITONG BAI
 * @since 2024-06-17
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    UsersServiceImpl usersService;
    @Autowired
    IRegionsService regionsService;
    @Autowired
    IHouseholdsService householdsService;
    @Autowired
    IRolesService rolesService;
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    IIdentificationCodesService identificationCodesService;
    @PostMapping("register_household")
    public ResponseEntity<String> register(@RequestBody Users users){
        try {
            Users existingUser=usersService.getUserByUsername(users.getUsername());
            if(existingUser!=null){
                return ResponseEntity.badRequest().body("注册失败，用户已存在");
            }
            // 追加角色
            Roles roles=rolesService.getRoleByRoleName("农户");
            users.setRole(roles.getRoleId());
            // 追加行政区
            Regions regions=new Regions();
            String idCard=users.getUsername();
            String addressCode=idCard.substring(0,6);
            regions=regionsService.getRegionsByRegionNumber(addressCode);
            if(regions==null){
                return ResponseEntity.badRequest().body("注册用户失败，身份证前六位有误");
            }
            users.setRegion(regions.getRegionName());
            usersService.save(users);
            // 追加农民
            Households households=new Households();
            households.setUserId(users.getUserId());
            householdsService.save(households);
            return ResponseEntity.ok().body("注册用户成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("register_leader")
    public ResponseEntity<String> registerLeader(@RequestBody Users users){
        try {
            Users existingUser=usersService.getUserByUsername(users.getUsername());
            if(existingUser!=null){
                return ResponseEntity.badRequest().body("注册失败，用户已存在");
            }
            // 验证身份
            IdentificationCodes identificationCodes = identificationCodesService.getIdentificationCodesByCode(users.getIdentificationCodes());
            if(identificationCodes == null){
                return ResponseEntity.badRequest().body("身份识别码错误");
            }
            // 追加角色
            Roles roles=rolesService.getRoleByRoleName("干部");
            users.setRole(roles.getRoleId());
            // 追加行政区
            Regions regions=regionsService.getRegionsByRegionName(identificationCodes.getRegion());
            users.setRegion(regions.getRegionName());
            usersService.save(users);
            return ResponseEntity.ok().body("注册用户成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("login")
    public ResponseEntity<String> login(@RequestBody Users users){
        try {
            Users users1=usersService.getUserByUsername(users.getUsername());
            if(users1==null){
                return ResponseEntity.badRequest().body("用户名不存在");
            }else if(!Objects.equals(users1.getPassword(), users.getPassword())){
                return ResponseEntity.badRequest().body("密码错误");
            }
            String token= jwtUtils.generateToken(users.getUsername());
            return ResponseEntity.ok().body(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("verify_token")
    public ResponseEntity<Boolean> verifyToken(@RequestBody String token){
        try {
            if(jwtUtils.verifyToken(token)){
                return ResponseEntity.ok().body(true);
            }else if(!jwtUtils.verifyToken(token)){
                return ResponseEntity.badRequest().body(false);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(false);
        }
        return ResponseEntity.badRequest().body(false);
    }
    @PostMapping("get_role")
    public ResponseEntity<Integer> getRole(@RequestBody Users users){
        try {
            Users users1=usersService.getUserByUsername(users.getUsername());
            return ResponseEntity.ok().body(users1.getRole());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(0);
        }
    }
    @PostMapping("get_userinfo")
    public ResponseEntity<Users> getUerinfo(@RequestBody Users users){
        Users user=usersService.getUserByUsername(users.getUsername());
        return ResponseEntity.ok().body(user);
    }
    @PostMapping("upload_avatar")
    public ResponseEntity<String> uploadAvatar(@RequestBody Users users){
        try {
            Users users1 = usersService.getUserByUsername(users.getUsername());
            users1.setAvatar(users.getAvatar());
            usersService.saveOrUpdate(users1);
            return ResponseEntity.ok().body(users1.getAvatar());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("get_users")
    public ResponseEntity<Page<Users>> getUsers( @RequestBody UserRequest userRequest ){
        int page=userRequest.getPage();
        int size=userRequest.getSize();
        Users users=userRequest.getUsers();
        Page<Users> usersPage=new Page<>(page,size);
        if(users==null){
            Page<Users> usersPage1=usersService.getUsers(usersPage);
            return ResponseEntity.ok().body(usersPage1);
        }else {
            Page<Users> usersPage1=usersService.getSearchUsers(usersPage,users);
            return ResponseEntity.ok().body(usersPage1);
        }
    }
    @PostMapping("update_users")
    public ResponseEntity<String> updateUser(@RequestBody Users users){
        Users real_users=usersService.getUserByUserId(users.getUserId());
        real_users.setRegion(users.getRegion());
        real_users.setRole(users.getRole());
        real_users.setRealName(users.getRealName());
        real_users.setUsername(users.getUsername());
        usersService.saveOrUpdate(real_users);
        return ResponseEntity.ok().body("更新用户成功");
    }
    @PostMapping("delete_user")
    public ResponseEntity<String> deleteUser(@RequestBody Users users){
        Users users1=usersService.getUserByUsername(users.getUsername());
        boolean isDeleted=usersService.deleteUserByUsername(users1.getUsername());
        if (isDeleted) {
            return ResponseEntity.ok("用户删除成功");
        } else {
            return ResponseEntity.badRequest().body("用户删除失败");
        }
    }
    @GetMapping("get_household_users")
    public ResponseEntity<Page<Users>> getHouseholdUsers(
            @RequestParam("region_name") String regionName,
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String keywords
    ) {
        Page<Users> userPage;
        QueryWrapper<Users> userQueryWrapper = new QueryWrapper<>();

        // 构建查询条件：regionName 模糊查询
        if (StringUtils.isNotBlank(regionName)) {
            userQueryWrapper.like("region", regionName).eq("role",1);
        }

        // keywords 作为二级查询条件进行模糊搜索
        if (StringUtils.isNotBlank(keywords)) {
            userQueryWrapper.and(wrapper -> wrapper
                    .like("real_name", keywords)
                    .or()
                    .like("username", keywords)
            );
        }

        // 分页查询
        Page<Users> pageResult = new Page<>(page, size);
        userPage = usersService.page(pageResult, userQueryWrapper);

        return ResponseEntity.ok().body(userPage);
    }
    @GetMapping("get_leader")
    public ResponseEntity<Page<Users>> getLeader(
            @RequestParam("region_name") String regionName,
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String keywords
    ) {
        Page<Users> userPage;
        QueryWrapper<Users> userQueryWrapper = new QueryWrapper<>();

        // 构建查询条件：regionName 模糊查询但不能完全一致
        if (StringUtils.isNotBlank(regionName)) {
            userQueryWrapper.like("region", regionName).ne("region", regionName).eq("role", 3);
        }


        // keywords 作为二级查询条件进行模糊搜索
        if (StringUtils.isNotBlank(keywords)) {
            userQueryWrapper.and(wrapper -> wrapper
                    .like("real_name", keywords)
                    .or()
                    .like("username", keywords)
            );
        }

        // 分页查询
        Page<Users> pageResult = new Page<>(page, size);
        userPage = usersService.page(pageResult, userQueryWrapper);
        return ResponseEntity.ok().body(userPage);
    }
}
